package website.lucaswork.survey.core.hessian;

import com.caucho.hessian.io.*;
import org.hibernate.Hibernate;
import org.hibernate.collection.internal.AbstractPersistentCollection;

import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;

public class SurveyCustomSerializerFactory extends SerializerFactory {

    private LazyListSerializer lazyListSerializer = new LazyListSerializer();

    @Override
    public Serializer getSerializer(Class cl) throws HessianProtocolException {
        if (AbstractPersistentCollection.class.isAssignableFrom(cl)) {
            return lazyListSerializer;
        } else if (LocalDate.class.isAssignableFrom(cl)) {
            return new LocalDateSerializer();
        }
        return super.getSerializer(cl);
    }

    @Override
    protected Deserializer getDefaultDeserializer(Class cl) {
        if (LocalDate.class.equals(cl)) {
            return new LocalDateDeserializer();
        }
        return super.getDefaultDeserializer(cl);
    }

    private static class LazyListSerializer implements Serializer {

        private CollectionSerializer delegate = new CollectionSerializer();

        @Override
        public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
            if (Hibernate.isInitialized(obj)) {
                delegate.writeObject(new ArrayList(((Collection) obj)), out);
            } else {
                delegate.writeObject(new ArrayList(), out);
            }
        }
    }
}
